<template>
  <div class="attendance-page">
    <div class="page-header">
      <h2 class="title">考勤管理</h2>
      <div class="actions">
        <el-date-picker
          v-model="query.dateRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          size="small"
          style="width: 280px"
        />
        <el-select v-model="query.department" placeholder="部门" size="small" style="width: 180px">
          <el-option label="全部部门" value="" />
          <el-option v-for="dept in departments" :key="dept" :label="dept" :value="dept" />
        </el-select>
        <el-input v-model="query.keyword" placeholder="姓名/工号" size="small" style="width: 200px" />
        <el-button type="primary" size="small" @click="handleSearch">查询</el-button>
        <el-button size="small" @click="handleReset">重置</el-button>
        <el-button type="success" size="small" @click="handleExport">导出报表</el-button>
      </div>
    </div>

    <div class="content-grid">
      <div class="left">
        <el-card class="table-card">
          <template #header>
            <div class="card-header">
              <span class="card-title">考勤记录</span>
              <div class="right-tools">
                <el-switch v-model="onlyAbnormal" active-text="仅看异常" />
              </div>
            </div>
          </template>
          <el-table :data="filteredData" height="520" stripe>
            <el-table-column prop="date" label="日期" width="110" />
            <el-table-column prop="empId" label="工号" width="100" />
            <el-table-column prop="name" label="姓名" width="110" />
            <el-table-column prop="department" label="部门" width="120" />
            <el-table-column prop="checkIn" label="上班打卡" width="120" />
            <el-table-column prop="checkOut" label="下班打卡" width="120" />
            <el-table-column prop="duration" label="工时(h)" width="100" />
            <el-table-column prop="status" label="状态" />
            <el-table-column label="操作" width="140">
              <template #default="{ row }">
                <el-button link type="primary" size="small" @click="handleAdjust(row)">更正</el-button>
                <el-button link type="danger" size="small" @click="handleMarkAbsence(row)">标记缺勤</el-button>
              </template>
            </el-table-column>
          </el-table>
          <div class="pagination">
            <el-pagination
              background
              layout="prev, pager, next, jumper"
              :page-size="20"
              :total="filteredData.length"
            />
          </div>
        </el-card>
      </div>

      <div class="right">
        <el-card class="stat-card">
          <template #header><span>当月考勤概览</span></template>
          <ul class="stat-list">
            <li><span>应出勤天数</span><b>{{ overview.shouldDays }}</b></li>
            <li><span>平均出勤率</span><b>{{ overview.attendanceRate }}%</b></li>
            <li><span>迟到次数</span><b>{{ overview.lateCount }}</b></li>
            <li><span>早退次数</span><b>{{ overview.earlyLeaveCount }}</b></li>
            <li><span>缺勤天数</span><b>{{ overview.absentDays }}</b></li>
          </ul>
        </el-card>

        <el-card class="rule-card">
          <template #header><span>考勤规则</span></template>
          <div class="rules">
            <div>上班时间：09:00</div>
            <div>下班时间：18:00</div>
            <div>迟到阈值：09:10</div>
            <div>早退阈值：17:50</div>
          </div>
          <div class="rule-actions">
            <el-button type="primary" size="small" @click="handleEditRules">编辑规则</el-button>
          </div>
        </el-card>
      </div>
    </div>

    <el-dialog v-model="adjustDialog.visible" title="更正打卡" width="420px" class="adjust-dialog">
      <el-form :model="adjustDialog.form" label-width="88px" class="adjust-form">
        <el-form-item label="上班打卡" class="adjust-form-item">
          <el-time-picker v-model="adjustDialog.form.checkIn" placeholder="选择时间" style="width: 100%" />
        </el-form-item>
        <el-form-item label="下班打卡" class="adjust-form-item">
          <el-time-picker v-model="adjustDialog.form.checkOut" placeholder="选择时间" style="width: 100%" />
        </el-form-item>
        <el-form-item label="备注" class="adjust-form-item">
          <el-input type="textarea" v-model="adjustDialog.form.remark" rows="3" style="width: 100%" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="adjust-footer">
          <el-button @click="adjustDialog.visible=false">取消</el-button>
          <el-button type="primary" @click="submitAdjust">提交</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

type AttendanceRow = {
  date: string
  empId: string
  name: string
  department: string
  checkIn: string
  checkOut: string
  duration: number
  status: '正常' | '迟到' | '早退' | '缺勤' | '请假'
}

const departments = ['全部部门','研发部','产品部','设计部','销售部','人资行政']
const query = ref<{ dateRange: [Date, Date] | null; department: string; keyword: string }>({
  dateRange: null,
  department: '',
  keyword: ''
})
const onlyAbnormal = ref(false)

// 示例数据
const tableData = ref<AttendanceRow[]>([
  { date: '2025-08-01', empId: 'E1001', name: '王小明', department: '研发部', checkIn: '09:05', checkOut: '18:10', duration: 8.1, status: '迟到' },
  { date: '2025-08-01', empId: 'E1023', name: '李四', department: '产品部', checkIn: '08:57', checkOut: '18:01', duration: 8.0, status: '正常' },
  { date: '2025-08-01', empId: 'E1099', name: '赵六', department: '销售部', checkIn: '-', checkOut: '-', duration: 0, status: '缺勤' },
  { date: '2025-08-02', empId: 'E1001', name: '王小明', department: '研发部', checkIn: '09:00', checkOut: '18:02', duration: 8.0, status: '正常' },
  { date: '2025-08-02', empId: 'E1099', name: '赵六', department: '销售部', checkIn: '09:20', checkOut: '17:48', duration: 7.5, status: '迟到' },
])

const overview = ref({ shouldDays: 22, attendanceRate: 96.8, lateCount: 12, earlyLeaveCount: 7, absentDays: 3 })

const filteredData = computed(() => {
  let data = tableData.value
  if (query.value.department) data = data.filter(d => d.department === query.value.department)
  if (query.value.keyword) data = data.filter(d => d.name.includes(query.value.keyword) || d.empId.includes(query.value.keyword))
  if (onlyAbnormal.value) data = data.filter(d => d.status !== '正常')
  // 可按日期区间进一步过滤
  return data
})

function getTime(dateStr: string) {
  const d = new Date();
  const [h, m] = dateStr.split(':');
  d.setHours(Number(h));
  d.setMinutes(Number(m));
  d.setSeconds(0);
  d.setMilliseconds(0);
  return d;
}
const DEFAULT_CHECKIN = getTime('09:00');
const DEFAULT_CHECKOUT = getTime('18:00');
const adjustDialog = ref({
  visible: false,
  form: { checkIn: DEFAULT_CHECKIN, checkOut: DEFAULT_CHECKOUT, remark: '' } as { checkIn: Date; checkOut: Date; remark: string }
})

const handleSearch = () => {
  ElMessage.success('已按条件过滤（示例数据）')
}

const handleReset = () => {
  query.value = { dateRange: null, department: '', keyword: '' }
  onlyAbnormal.value = false
}
const handleEditRules = () => {
  adjustDialog.value.form = {
    checkIn: getTime('09:00'),
    checkOut: getTime('18:00'),
    remark: ''
  };
  adjustDialog.value.visible = true;
}
const handleExport = () => {
  ElMessage.success('导出成功（示例）')
}

const handleAdjust = (row: AttendanceRow) => {
  adjustDialog.value.visible = true;
  adjustDialog.value.form = {
    checkIn: typeof row.checkIn === 'string' && row.checkIn.match(/^\d{2}:\d{2}$/) ? getTime(row.checkIn) : DEFAULT_CHECKIN,
    checkOut: typeof row.checkOut === 'string' && row.checkOut.match(/^\d{2}:\d{2}$/) ? getTime(row.checkOut) : DEFAULT_CHECKOUT,
    remark: ''
  };
}

const submitAdjust = () => {
  adjustDialog.value.visible = false
  ElMessage.success('更正已提交审核')
}

const handleMarkAbsence = (row: AttendanceRow) => {
  ElMessageBox.confirm(`确认将 ${row.name} 标记为缺勤？`, '提示', { type: 'warning' }).then(() => {
    row.status = '缺勤'
    row.checkIn = '-'
    row.checkOut = '-'
    row.duration = 0
    ElMessage.success('已标记为缺勤')
  })
}
</script>

<style scoped>
.attendance-page { padding: 16px; }
/* 优化更正打卡弹窗表单样式 */
.adjust-dialog .el-dialog__body {
  padding-top: 18px;
  padding-bottom: 10px;
}
.adjust-form {
  display: flex;
  flex-direction: column;
  gap: 12px;
  margin-top: 8px;
}
.adjust-form-item .el-form-item__label {
  font-weight: 500;
  color: #409eff;
  font-size: 15px;
}
.adjust-form-item .el-form-item__content {
  width: 100%;
}
.adjust-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  padding-top: 8px;
}
.page-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 16px;
  padding: 12px 16px;
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0,0,0,0.06);
}
.title { font-size: 20px; font-weight: 600; color: #303133; margin: 0; }
.actions { display: flex; gap: 10px; align-items: center; flex-wrap: wrap; }

.content-grid {
  display: grid;
  grid-template-columns: minmax(0, 1fr) 320px; /* 左侧可压缩，右侧固定宽度 */
  gap: 16px;
  align-items: start;
}
.left { min-width: 0; } /* 允许表格区域在网格中收缩 */
.right { width: 320px; }
.table-card { }
.pagination { display: flex; justify-content: flex-end; padding-top: 12px; }

.card-header { display: flex; align-items: center; justify-content: space-between; }
.card-title { font-weight: 600; color: #303133; }

.stat-card .stat-list { list-style: none; padding: 0; margin: 0; display: grid; grid-template-columns: 1fr 1fr; gap: 12px; }
.stat-card .stat-list li { display: flex; justify-content: space-between; padding: 12px 14px; background: #f9fafb; border-radius: 10px; }
.stat-card .stat-list li b { font-size: 18px; color: #409eff; font-weight: 700; }

.rule-card .rules { display: grid; grid-template-columns: 1fr 1fr; gap: 8px; color: #606266; }
.rule-actions { text-align: right; margin-top: 12px; }

@media (max-width: 1200px) {
  .content-grid { grid-template-columns: 1fr; }
  .right { width: 100%; }
}
</style>

